;The number 3797 has an interesting property.
;Being prime itself, it is possible to continuously remove digits from left to right, and remain prime
; at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3.
;
;Find the sum of the only eleven primes that are both truncatable from left to right and right to left.
;NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.

(ns pe.p37
  (:use pe.primes)
  (:use pe.seq)
  (:use clojure.contrib.math)
  (:use pe.digits))

(defn trunc-right [n] (quot n 10))

(defn trunc-left [n]
  (let [dig-cnt (int (Math/log10 n)) pow10 (expt 10 dig-cnt)]
    (rem n pow10)))

(defn truncatable-prime? [f n]
  (cond
    (= 0 n) true ; end of loop
    (not (prime? n)) false
    :else (recur f (f n))))

(def truncatable-left? (partial truncatable-prime? trunc-left))
(def truncatable-right? (partial truncatable-prime? trunc-right))

(defn satisifies? [n]
  (let [ok (and (truncatable-left? n) (truncatable-right? n))] ok))

(println (reduce + (take 11 (filter satisifies? (filter #(> % 10) primes)))))
; 748317